package io.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * TCP客户端：对应 Server1
 * @author ben
 * @date 2021-11-01 20:58:28 CST
 */
public class Client1 {

	public static void main(String[] args) {
		// 服务器信息
		String serverName = "localhost";
		int serverPort = 10000;
		
		System.out.println("连接到主机：" + serverName + " ，端口号：" + serverPort);
		try {
			Socket client = new Socket(serverName, serverPort);
			
			// 超时时间
			client.setSoTimeout(30);
			
			System.out.println("远程主机地址：" + client.getRemoteSocketAddress());
			System.out.println("client.getKeepAlive()=" + client.getKeepAlive());
			
			try {
				for (int i=0; i<10; i++) {
					System.out.println("i=" + i);
					sendAndReceiveData(client);
					TimeUnit.SECONDS.sleep(2);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			// 关闭客户端
			client.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 单次发送接收
	 * @author ben
	 * @date 2021-11-01 21:07:59 CST
	 * @param client
	 * @throws IOException
	 */
	private static void sendAndReceiveData(Socket client) throws IOException {
		// 发送消息
		OutputStream outToServer = client.getOutputStream();
		DataOutputStream out = new DataOutputStream(outToServer);
		out.writeUTF("Hello from " + client.getLocalSocketAddress() + ", 客户端时间=" + new Date());
		
		// 读取信息-来自服务器
		InputStream inFromServer = client.getInputStream();
		DataInputStream in = new DataInputStream(inFromServer);
		System.out.println("服务器响应： " + in.readUTF());
	}

}
